import { createCustomComponent } from '@/router/generator-routers';
/**
 *
 * @param {*} router
 * @param {*} params params中，accessPath(访问路径)和cmptPath(新打开页面调用组件路径)为必有属性
 * @param {*} currentMicroApp 当前页签的子应用信息
 * @returns
 */
// 生成动态路由，并打开新的标签页
export function openNewPlatformTabCommon($router, params, currentMicroApp) {
  const { siteType, router, query = {} } = params;
  if (siteType === 0 && !router.component) return;

  // 在主应用注册路由
  const { path } = router;
  const routeExists = $router.getRoutes().some((route) => route.path === path);
  let routerObj = null;
  if (!routeExists) {
    // 路由不存在时注册
    const componentId = Math.random().toString(36)
      .substring(2)
      .slice(0, 6);
    const componentName = `microApp${Date.now()}${componentId}`;
    const component = siteType === 0 ? router.component : 'avic/micro-app/micropage/MicroPage';
    // eslint-disable-next-line prefer-template
    const customComponent = createCustomComponent(componentName, component);
    routerObj = {
      path,
      component: customComponent,
      name: componentName,
      meta: {
        componentName,
        component,
        siteType,
        fullPath: path,
        ...currentMicroApp,
        ...router.meta
      }
    };
    $router.addRoute('RouteView', routerObj);
  } else {
    const routesList = $router.getRoutes().filter((route) => route.path === path);
    if (routesList.length > 0) {
      const [obj] = routesList;
      routerObj = { ...obj };
    }
  }

  // 打开注册的路由
  $router.push({ path: routerObj.path, query });

  // 业务定制化内容 ---在浏览器中缓存注册的路由的路由信息
  if (!window.localStorage) {
    return;
  }
  const tabRecordsStorage = window.localStorage.getItem('tabRecords');
  let newTabRecords = [];
  if (tabRecordsStorage) {
    newTabRecords = JSON.parse(tabRecordsStorage);
  }
  const isContain = newTabRecords.some((one) => one.routerInfo.path === routerObj.path);
  if (!isContain) {
    // routerObj.component = routerObj.meta.cmptPath;
    const routerInfo = {
      ...router,
      meta: {
        ...routerObj.meta
      }
    };
    newTabRecords.push({ routerInfo, query });
  }
  window.localStorage.setItem('tabRecords', JSON.stringify(newTabRecords));
}
